<script>
import TIM from "tim-wx-sdk";
import COS from "cos-wx-sdk-v5";


export default {
  onLaunch: function () {
    const that = this;
    
    // 冷启动重新登录获取用户信息,重新登陆腾讯IM
    that.$store.dispatch("getUserInfo").then(()=>{
      that.$store.dispatch("loginIm");
    })

    uni.getSystemInfo({
      success: function (res) {
        const deviceInfo = {
          safeArea: res.safeArea,
          language: res.language,
          model: res.model,
          system: res.system,
          statusBarHeight: res.statusBarHeight, // 状态栏高度
          navbarHeight: res.statusBarHeight + 44, // uview导航栏高度
        };
        console.log(deviceInfo, "设备信息");
        that.$store.commit("SET_DEVICEINFO", deviceInfo);
      },
    });
    

    // 初始化腾讯IM
    uni.setStorageSync(`TIM_${that.$store.state.SDKAppID}_isTUIKit`, true);
    // 重点注意： 为了 uni-app 更好地接入使用 tim，快速定位和解决问题，请勿修改 uni.$TUIKit 命名。
    // 如果您已经接入 tim ，请将 uni.tim 修改为 uni.$TUIKit。
    uni.$TUIKit = TIM.create({ SDKAppID: that.$store.state.SDKAppID });
    // 注册 COS SDK 插件
    uni.$TUIKit.registerPlugin({ "cos-wx-sdk": COS });
    // 如果您已创建了 tim，请将 tim 实例挂载在 wx 上，且不可以修改 wx.$TIM（修改变量可能导致 TUICalling 组件无法正常使用）, 完成 TUICalling 初始化，
    // 如果您没有创建，可以不传
    // #ifdef MP-WEIXIN
    wx.$TIM = uni.$TUIKit;
    // #endif
    uni.$TUIKitTIM = TIM;
    uni.$TUIKitEvent = TIM.EVENT;
    uni.$TUIKitVersion = TIM.VERSION;
    uni.$TUIKitTypes = TIM.TYPES; // 监听系统级事件
    uni.$resetLoginData = this.resetLoginData();
    uni.$TUIKit.setLogLevel(3); // 输入日志级别
    uni.$TUIKit.on(uni.$TUIKitEvent.SDK_READY, this.onSDKReady);
    uni.$TUIKit.on(uni.$TUIKitEvent.SDK_NOT_READY, this.onSdkNotReady);
    uni.$TUIKit.on(uni.$TUIKitEvent.KICKED_OUT, this.onKickedOut);
    uni.$TUIKit.on(uni.$TUIKitEvent.ERROR, this.onTIMError);
    uni.$TUIKit.on(uni.$TUIKitEvent.NET_STATE_CHANGE, this.onNetStateChange);
    uni.$TUIKit.on(uni.$TUIKitEvent.SDK_RELOAD, this.onSDKReload);
    uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.onMessageReceived);
  },
  globalData: {
    // userInfo: userID userSig token phone
    // userInfo: userID userSig token phone
    userInfo: {
      userID: "",
      userSig: "",
    },
    // 个人信息
    userProfile: {},
    isTUIKit: true,
  },
  methods: {
    onTIMError(event) {
      const that = this
      console.info("聊天-SDK遇到错误时触发", event.data.message);
      uni.$u.throttle(() => {
        that.$store.dispatch("loginIm");
      }, 10000);
    },
    onSDKReady({ name }) {
      console.info("聊天-SDK进入ready状态时触发", name);
      const isSDKReady = name === uni.$TUIKitEvent.SDK_READY ? true : false;
      uni.$emit("isSDKReady", {isSDKReady}); 
      this.$store.commit("SET_ISSDKREADY", isSDKReady);
      this.$store.dispatch("dissolveGroup"); // 解散群组
      this.$store.dispatch("updateMyProfile"); // 更新用户信息
    },
    onSdkNotReady() {
      console.info("聊天-SDK进入not ready状态时触发");
    },
    onNetStateChange(event) {
      console.info("聊天-网络状态改变通知", event);
      // v2.5.0 起支持
      // event.data.state 当前网络状态，枚举值及说明如下：
      // TIM.TYPES.NET_STATE_CONNECTED - 已接入网络
      // TIM.TYPES.NET_STATE_CONNECTING - 连接中。很可能遇到网络抖动，SDK 在重试。接入侧可根据此状态提示“当前网络不稳定”或“连接中”
      // TIM.TYPES.NET_STATE_DISCONNECTED - 未接入网络。接入侧可根据此状态提示“当前网络不可用”。SDK 仍会继续重试，若用户网络恢复，SDK 会自动同步消息
    },
    onSDKReload() {
      console.info("聊天-SDK重启");
    },
    onKickedOut() {
      this.$store.dispatch("loginOut")
      uni.showModal({
        title: '温馨提示',
        content: '该账号在其它设备登录',
        showCancel: false
      });
    },
    onMessageReceived(event) {
      const that = this
      const userID = that.$store.state.userInfo.id + ''
      const msgObj = event.data[event.data.length-1]
      console.log(event,'接收到新消息');

      // 接收到关注公众号和取关的消息
      if(msgObj.conversationID === "C2Cadministrator"){
        this.$store.dispatch("getUserInfo");
        uni.$TUIKit.deleteConversation(msgObj.conversationID).then(()=>{
          that.$store.dispatch("getTotalUnreadMessageCount"); // 获取未读消息
        })
        return
      }
      const pages = getCurrentPages();//页面路由实例
      const { route, options } = pages[pages.length -1]
      if(route === 'pagesB/TUI-Chat/chat' && msgObj.conversationID === options.conversationID){
        uni.$TUIKit.setMessageRead({ conversationID: msgObj.conversationID }); // 清空当前聊天窗口的未读消息
      }else if(msgObj.conversationType === 'C2C'){
        that.$store.dispatch("getTotalUnreadMessageCount"); // 获取未读消息
      }

      // 群消息,并且有@自己
      if(msgObj.conversationType === 'GROUP'){
        const payloadData = msgObj.payload?.text ?? msgObj.payload?.data
        console.log(payloadData,'群消息内容主体');
        // const isAt = msgObj.atUserList.includes(userID) // 是否有@自己
        const newMsg = JSON.parse(payloadData)
        
        if(newMsg.action === 'evtImMsgCall'){
          if(route === 'pagesB/meeting/callPanel' || route === 'pagesB/meeting/index'){
            console.log('正在通話，請勿打擾');
            that.$store.dispatch("sendMessage",{groupID: newMsg.data.imGroupId,action: 'evtImMsgbusy',replyMsg: newMsg}); // 发送忙线消息
          }else{
            console.log(newMsg,'對方邀請你視頻通话');
            that.$store.commit("SET_CURRENTMESSAGE", newMsg);
            that.$store.commit("SET_CELLINFO", {
              orderNo: newMsg.data.orderNo,
              meetingRoomNumber: newMsg.data.meetingNum,
              password: newMsg.data.meetingPwd,
              id: newMsg.data.sendUserId,
              userName: newMsg.data.sendUserName,
              headimg: newMsg.data.sendUserIcon
            }); // 呼叫信息
            uni.navigateTo({url: `/pagesB/meeting/callPanel?meetingStatus=2`})
          }
        }else if(newMsg.action === 'evtImMsgAnswer'){
          console.log('對方已接聽，加入視頻通話');
          if(route === 'pagesB/meeting/callPanel'){
            that.$store.commit("SET_CURRENTMESSAGE", newMsg);
            uni.redirectTo({url: `/pagesB/meeting/index`})
          }
        }else if(newMsg.action === 'evtImMsgHangUp'){
          console.log('對方拒絕接聽，退出視頻通話');
          if(route === 'pagesB/meeting/callPanel'){ 
            uni.showToast({
              title: '对方拒绝接听',
              icon: 'none',
              complete: () => {
                setTimeout(() => {
                  that.goBack()
                  that.$store.commit("SET_CURRENTMESSAGE", {});
                  that.$store.commit("SET_CELLINFO", {});
                  that.$store.dispatch("dissolveGroup"); // 解散群组
                  that.$store.dispatch("reportStatus",{status: 3}); // 改为上线
                }, 1500);
              }
            })
          }
        }else if(newMsg.action === 'evtImMsgbusy'){
          console.log('對方正在通話中');
          if(route === 'pagesB/meeting/callPanel'){
            uni.showToast({
              title: '忙线中,请稍后再拨',
              icon: 'none',
              complete: () => {
                setTimeout(() => {
                  that.goBack()
                  that.$store.commit("SET_CURRENTMESSAGE", {});
                  that.$store.commit("SET_CELLINFO", {});
                  that.$store.dispatch("dissolveGroup"); // 解散群组
                  that.$store.dispatch("reportStatus",{status: 3}); // 改为上线
                }, 1500);
              }
            })
          }
        }else if(newMsg.action === 'evtImMsgCallerHangUp'){
          console.log('呼叫者挂断');
          if(route === 'pagesB/meeting/callPanel'|| route === 'pagesB/meeting/index'){
            uni.showToast({
              title: '对方已取消通话',
              icon: 'none',
              complete: () => {
                setTimeout(() => {
                  that.goBack()
                  // that.goPage('/pages/index/index') // 回到首页
                  that.$store.commit("SET_CURRENTMESSAGE", {});
                  that.$store.commit("SET_CELLINFO", {});
                  that.$store.dispatch("dissolveGroup"); // 解散群组
                  that.$store.dispatch("reportStatus",{status: 3}); // 改为上线
                }, 1500);
              }
            })
          }
        }else if(newMsg.action === 'evtImMsgHostAllEndOfCall'){
          console.log('主持人挂断');
          if(route === 'pagesB/meeting/callPanel'|| route === 'pagesB/meeting/index'){
            uni.showToast({
              title: '主持人已结束通话',
              icon: 'none',
              complete: () => {
                setTimeout(() => {
                  that.goBack()
                  // that.goPage('/pages/index/index') // 回到首页
                  that.$store.commit("SET_CURRENTMESSAGE", {});
                  that.$store.commit("SET_CELLINFO", {});
                  that.$store.dispatch("dissolveGroup"); // 解散群组
                  that.$store.dispatch("reportStatus",{status: 3}); // 改为上线
                }, 1500);
              }
            })
          }
        }else if(newMsg.action === 'evtImMsgMemberAllEndOfCall'){
          console.log('两人通话,对方已挂断');
          if(route === 'pagesB/meeting/callPanel'|| route === 'pagesB/meeting/index'){
            uni.showToast({
              title: '对方已结束通话',
              icon: 'none',
              complete: () => {
                setTimeout(() => {
                  that.goBack()
                  // that.goPage('/pages/index/index') // 回到首页
                  that.$store.commit("SET_CURRENTMESSAGE", {});
                  that.$store.commit("SET_CELLINFO", {});
                  that.$store.dispatch("dissolveGroup"); // 解散群组
                  that.$store.dispatch("reportStatus",{status: 3}); // 改为上线
                }, 1500);
              }
            })
          }
        }else if(newMsg.action === 'evtImMsgHostEndOfCall'){
          console.log('主持人退出会议,但不结束通话');
        }else if(newMsg.action === 'evtImMsgHostMemberEndOfCall'){
          console.log('对方退出会议,此人非主持人');
        }else{
          console.error('pad端未知的消息类型',newMsg);
        }
      }
      return
    },
    // 初始化数据
    resetLoginData() {
      this.globalData.expiresIn = '';
      this.globalData.sessionID = '';
      this.globalData.userInfo = {
        userID: '',
        userSig: '',
        token: '',
        phone: ''
      };
      this.globalData.userProfile = null;
    },
  },
  onShow: function (res) {
    const { path } = res;
    if(path.indexOf('expertIdentity') !== -1){
		  this.$store.commit("SET_USERTYPE", 0);
    }else{
		  this.$store.commit("SET_USERTYPE", 1);
    }
  },
  onHide: function () {},
};
</script>

<style lang="scss">
@import "uview-ui/index.scss";
@import "@/styles/global.scss";
</style>
